/*
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2021-08-19 09:27:52
 * @LastEditors: GGB
 * @LastEditTime: 2021-08-19 17:24:22
 */
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_data_center/components/custom_btn.dart';
import 'package:flutter_data_center/components/custom_textfield_widget.dart';
import 'package:flutter_data_center/controller/warning_controller.dart';
import 'package:flutter_data_center/screens/warning/preview/warning_preview_screen.dart';
import 'package:flutter_data_center/utills/color_utils.dart';
import 'package:flutter_data_center/utills/navigator_utils.dart';
import 'package:flutter_data_center/utills/toast_utils.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

import 'components/menus_popup.dart';
import 'components/warning_type.dart';

class WarningAddScreen extends StatefulWidget {
  const WarningAddScreen({Key key}) : super(key: key);
  static String routeName = "/warning_add";

  @override
  _WarningAddScreenState createState() => _WarningAddScreenState();
}

class _WarningAddScreenState extends State<WarningAddScreen> {
  WarningController _warningController = Get.put(WarningController());
  FocusNode _addressFocusNode = new FocusNode();
  FocusNode _descFocusNode = new FocusNode();
  TextEditingController _addressEditController = new TextEditingController();
  TextEditingController _descEditController = new TextEditingController();

  File image;
  final ImagePicker picker = ImagePicker();

  List<XFile> files = [];

  String type = "building";
  String level = "a";
  String levalString = "一级";

  // 打开文件管理器

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: buildAppBar(),
        body: SafeArea(
          child: SingleChildScrollView(
            physics: BouncingScrollPhysics(),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  buildTitle(),
                  SizedBox(height: 30),
                  buildAddImage(),
                  SizedBox(height: 30),
                  Text("任务名称", style: TextStyle(fontSize: 18)),
                  SizedBox(height: 10),
                  buildAddress(context),
                  SizedBox(height: 30),
                  WarningType(
                    types: _warningController.warningsType,
                    type: type,
                    onTap: (value) {
                      setState(() {
                        type = value;
                      });
                    },
                  ),
                  SizedBox(height: 30),
                  Text("描述", style: TextStyle(fontSize: 18)),
                  SizedBox(height: 10),
                  buildDesc(context),
                  SizedBox(height: 30),
                  CustomBtn(
                    text: '上报',
                    onTap: () {},
                    height: 45,
                    width: 365,
                    style: TextStyle(fontSize: 14),
                    primary: gColor("#08D187"),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
// 构建照片上传
  Container buildAddImage() {
    return Container(
      width: double.infinity,
      alignment: Alignment.center,
      height: 135,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: gColor("#EEF8F4"),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: [
          SizedBox(width: 10),
          InkWell(
            borderRadius: BorderRadius.circular(45),
            onTap: chooseImage,
            child: Container(
              width: 45,
              height: 45,
              decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.2),
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.add),
            ),
          ),
          SizedBox(width: 10),
          if (files.length != 0)
            Expanded(
              child: Container(
                height: 120,
                child: ListView.builder(
                  physics: BouncingScrollPhysics(),
                  scrollDirection: Axis.horizontal,
                  itemCount: files.length,
                  itemBuilder: (context, index) => Container(
                    width: 120,
                    height: 120,
                    padding: EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Stack(
                      children: [
                        Positioned.fill(
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: InkWell(
                              onTap: () {
                                NavigatorUtils.pushPageByFade(
                                  context: context,
                                  targetPage:
                                      WarningPreviewScreen(files: files),
                                  isReplace: false,
                                  startMills: 500,
                                );
                              },
                              child: Hero(
                                tag: files[index].name,
                                child: Semantics(
                                  child: Image.file(
                                    File(files[index].path),
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        Positioned(
                          top: 5,
                          right: 5,
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.grey.withOpacity(0.2),
                              shape: BoxShape.circle,
                            ),
                            child: InkWell(
                              onTap: () {
                                files.removeAt(index);
                                setState(() {});
                              },
                              child: Icon(
                                Icons.close,
                                color: Colors.red,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

// 构建顶部标题
  Row buildTitle() {
    return Row(
      children: [
        Text(
          "上传照片",
          style: TextStyle(
            fontSize: 28,
          ),
        ),
        Spacer(),
        Text(
          levalString,
          style: TextStyle(
            fontSize: 14,
            color: gColor("#929292"),
          ),
        ),
        MenusPopup(
          level: level,
          menus: _warningController.warningLevel,
          onTap: (String value) {
            print(value);
            for (var item in _warningController.warningLevel) {
              if (item.key == value) {
                levalString = item.value;
              }
            }
            setState(() {
              level = value;
            });
          },
        ),
      ],
    );
  }

// 构建appBar
  AppBar buildAppBar() {
    return AppBar(
      backgroundColor: Colors.transparent,
      centerTitle: true,
      title: Text(
        "上报隐患",
        style: TextStyle(
          fontSize: 18,
        ),
      ),
      elevation: 0,
    );
  }

// 构建地址输入框
  TextFieldWidget buildAddress(BuildContext context) {
    return TextFieldWidget(
      submit: (value) {
        if (value == null) {
          ToastUtils.showToast("请输入隐患地点");
          FocusScope.of(context).requestFocus(_addressFocusNode);
          return;
        }
        _addressFocusNode.unfocus();
        FocusScope.of(context).requestFocus(_addressFocusNode);
      },
      focusNode: _addressFocusNode,
      controller: _addressEditController,
      obscureText: false,
    );
  }

// 构建预警魔术输入框
  TextFieldWidget buildDesc(BuildContext context) {
    return TextFieldWidget(
      submit: (value) {
        if (value == null) {
          ToastUtils.showToast("请输入描述");
          FocusScope.of(context).requestFocus(_descFocusNode);
          return;
        }
        _descFocusNode.unfocus();
        FocusScope.of(context).requestFocus(_descFocusNode);
      },
      focusNode: _descFocusNode,
      controller: _descEditController,
      obscureText: false,
      maxLines: 4,
    );
  }

// 构建选择的类型
  buildType() {
    return Row(
      children: _warningController.warningsType
          .map(
            (e) => Flexible(
              child: RadioListTile(
                activeColor: Theme.of(context).primaryColor,
                tileColor: gColor("#969696"),
                title: Text(e.value),
                value: e.key,
                groupValue: type,
                onChanged: (value) {
                  setState(() {
                    type = e.key;
                  });
                },
              ),
            ),
          )
          .toList(),
    );
  }

// 选择照片的来源方式
  chooseImage() async {
    if (files.length > 8) return;
    await showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          title: Text('请选择'),
          message: Text('选择图片来源'),
          actions: <Widget>[
            CupertinoActionSheetAction(
              child: Text('相机'),
              onPressed: () async {
                final XFile photo =
                    await picker.pickImage(source: ImageSource.camera);
                setState(() {
                  files.add(photo);
                });
                Navigator.of(context).pop();
              },
              isDefaultAction: false,
            ),
            CupertinoActionSheetAction(
              child: Text('相册'),
              onPressed: () async {
                final List<XFile> images = await picker.pickMultiImage();
                Navigator.of(context).pop();
                if ((images.length + files.length) > 9) {
                  ToastUtils.showToast("最多只能上传9张照片");
                  return;
                }
                setState(() {
                  files = [...files, ...images];
                });
              },
              isDestructiveAction: false,
            ),
          ],
        );
      },
    );
  }
}
